/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.cooperation.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson2.JSON;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.cooperation.entity.BizCooperationExcel;
import vip.xiaonuo.biz.modular.cooperation.util.ExcelUtil;
import vip.xiaonuo.biz.modular.file.provider.BizFileApiProvider;
import vip.xiaonuo.biz.modular.motion.entity.BizMotion;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.cooperation.entity.BizCooperation;
import vip.xiaonuo.biz.modular.cooperation.mapper.BizCooperationMapper;
import vip.xiaonuo.biz.modular.cooperation.param.BizCooperationAddParam;
import vip.xiaonuo.biz.modular.cooperation.param.BizCooperationEditParam;
import vip.xiaonuo.biz.modular.cooperation.param.BizCooperationIdParam;
import vip.xiaonuo.biz.modular.cooperation.param.BizCooperationPageParam;
import vip.xiaonuo.biz.modular.cooperation.service.BizCooperationService;
import vip.xiaonuo.dev.api.DevFileApi;
import vip.xiaonuo.dev.api.DevWechatApi;
import vip.xiaonuo.dev.modular.wechat.provider.WechatApiProvider;
import vip.xiaonuo.sys.api.SysOrgApi;
import vip.xiaonuo.sys.api.SysUserApi;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static vip.xiaonuo.common.enums.CommonExceptionEnum.ERROR416;

/**
 * 互助金成员信息记录表Service接口实现类
 *
 * @author 薛守立
 * @date  2024/09/08 14:54
 **/
@Slf4j
@Service
public class BizCooperationServiceImpl extends ServiceImpl<BizCooperationMapper, BizCooperation> implements BizCooperationService {

    @Resource
    private DevFileApi devFileApi;

    @Resource
    private BizFileApiProvider bizFileApiProvider;

    @Resource
    private SysUserApi sysUserApi;

    @Resource
    private SysOrgApi sysOrgApi;

    @Resource
    private DevWechatApi devWechatApi;


    @Override
    public Page<BizCooperation> page(BizCooperationPageParam bizCooperationPageParam, String status) {
        QueryWrapper<BizCooperation> queryWrapper = new QueryWrapper<BizCooperation>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizCooperationPageParam.getMemberName())) {
            queryWrapper.lambda().like(BizCooperation::getMemberName, bizCooperationPageParam.getMemberName());
        }
        if(ObjectUtil.isAllNotEmpty(bizCooperationPageParam.getSortField(), bizCooperationPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizCooperationPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizCooperationPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizCooperationPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizCooperation::getId);
        }
        // 10查询已经通过的名单
        if(status.equals("10")) queryWrapper.lambda().eq(BizCooperation::getApplyStatus, "20");
        // 20登录人查询范围
        if(status.equals("20")){
            queryWrapper.lambda().eq(BizCooperation::getCreateUser, StpUtil.getLoginIdAsString());
        }
        // 30查询待审批范围
        if(status.equals("30")){
            queryWrapper.lambda().eq(BizCooperation::getApplyStatus,"10");
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizCooperationAddParam bizCooperationAddParam) {
        BizCooperation bizCooperation = BeanUtil.toBean(bizCooperationAddParam, BizCooperation.class);
        bizCooperation.setApplyStatus("0");
        //根据组织ID查询 单位名称
        String orgId = bizCooperationAddParam.getMemberOrg();
        String orgNm = sysOrgApi.getNameById(orgId);
        bizCooperation.setOrgId(orgId);
        bizCooperation.setOrgName(orgNm);
        this.save(bizCooperation);
        // 更新文件管理器
        List<String> fileList = bizCooperationAddParam.getFileList();
        for(String fileId : fileList){
            bizFileApiProvider.updateFile(fileId, bizCooperation.getId(), "互助金申请文件");
        }
        String url = bizFileApiProvider.getFileUrl(fileList.get(0));
        bizCooperation.setApplyFileUrl(url);
        this.updateById(bizCooperation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizCooperationEditParam bizCooperationEditParam) {
        BizCooperation bizCooperation = this.queryEntity(bizCooperationEditParam.getId());
        BeanUtil.copyProperties(bizCooperationEditParam, bizCooperation);
        //根据组织ID查询 单位名称
        String orgId = bizCooperationEditParam.getMemberOrg();
        String orgNm = sysOrgApi.getNameById(orgId);
        bizCooperation.setOrgId(orgId);
        bizCooperation.setOrgName(orgNm);
        this.updateById(bizCooperation);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizCooperationIdParam> bizCooperationIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizCooperationIdParamList, BizCooperationIdParam::getId));
    }

    @Override
    public BizCooperation detail(BizCooperationIdParam bizCooperationIdParam) {
        return this.queryEntity(bizCooperationIdParam.getId());
    }

    @Override
    public BizCooperation queryEntity(String id) {
        BizCooperation bizCooperation = this.getById(id);
        if(ObjectUtil.isEmpty(bizCooperation)) {
            throw new CommonException("互助金成员信息记录表不存在，id值为：{}", id);
        }
        return bizCooperation;
    }

    @Override
    public String exportIn(MultipartFile file) {
        // 校验文件
        boolean s = ExcelUtil.checkExcelExtension(file);
        if(!s) throw new CommonException(ERROR416);
        // 读取上传的excel文件
        EasyExcel.read((File) file, BizCooperationExcel.class, new PageReadListener<BizCooperationExcel>(bizCooperationList -> {
            ArrayList<BizCooperation> resList = new ArrayList<>();
            for (BizCooperationExcel bizCooperation : bizCooperationList) {
                log.info("读到一条数据{}", JSON.toJSONString(bizCooperation));
                // 单独处理数据
            }
            // 批量保存数据
            this.saveBatch(resList);
        })).sheet().doRead();

        return "保存成功";
    }

    @Override
    public List<BizCooperation> getAllCooperation() {
        LambdaQueryWrapper<BizCooperation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(BizCooperation::getApplyStatus, "20");
        return this.list(lqw);
    }

    @Override
    public String uploadFile(MultipartFile file) {
        return devFileApi.storageFileWithReturnUrlLocal(file);
    }

    @Override
    public void apply(BizCooperationEditParam bizCooperationEditParam) {
        this.edit(bizCooperationEditParam);
        String subject = "";
        if(Objects.equals(bizCooperationEditParam.getApplyStatus(), "20")) subject="您的互助金审批已通过！请您及时缴纳当年互助金费用";
        if(Objects.equals(bizCooperationEditParam.getApplyStatus(), "30")) subject="您的互助金审批已被拒绝！请及时查询审批拒绝原因";
        BizCooperation biz = this.getById(bizCooperationEditParam.getId());
        if(biz==null) throw new CommonException("参数有误，请检查数据");
        if(!Objects.equals(bizCooperationEditParam.getApplyStatus(), "10") && !Objects.equals(bizCooperationEditParam.getApplyStatus(), "0")){
            List<String> list = new ArrayList<>();
            list.add(sysUserApi.getWechatId(biz.getCreateUser()));
            devWechatApi.sendWechat(list, "text",subject, "user");
        }

    }
}
